package com.depository.oss.service.imp;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.depository.api.service.OSSService;
import com.depository.oss.DefaultOSSClient;
import com.depository.oss.config.OSSParameter;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;

@Component("ossService")
public class OSSServiceImp implements OSSService {

    @Autowired
    private static OSSParameter ossParameter;

    private static final Logger logger = Logger.getLogger(OSSServiceImp.class);

    @Override
    public String putObject(byte[] content, String fileName, String targetPath, String suffixName) {
        String url = null;
        fileName=targetPath+"/"+fileName+"."+suffixName;
        try {
            OSSClient client = DefaultOSSClient.getDefaultOSSClient();

            if(content != null){
                client.putObject(new PutObjectRequest(ossParameter.BUCKETNAME, fileName, new ByteArrayInputStream(content)));
            }
            url = ossParameter.ENDPOINT.replaceFirst("http://","http://"+ossParameter.BUCKETNAME+".")+"/"+fileName;       //上传成功再返回的文件路径
        } catch (OSSException e) {
            logger.error("OSSUtil error:{}" ,e);
            throw new RuntimeException(e);
        }catch (ClientException e) {
            logger.error("OSSUtil error:{}",e);
            throw new RuntimeException(e);
        }finally{
            logger.info("OSSurl:" + url );
            DefaultOSSClient.shutdownOSSClient();
        }

        return url;
    }
}
